package com.mymall.serve.service;
import java.time.LocalDateTime;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mymall.serve.dto.param.RoleUserParam;
import com.mymall.serve.entity.SysRoleUser;
import com.mymall.serve.mapper.SysRoleUserlinkMapper;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.List;

@Service
public class SysRoleUserLinkService extends ServiceImpl<SysRoleUserlinkMapper, SysRoleUser> {

    public void addRoleToUser(RoleUserParam rParam) {
        List<Long> userIds = rParam.getUserIds();
        List<Long> roleIds = rParam.getRoleIds();
        this.deleteByUserIds(userIds);

        List<SysRoleUser> roleUserList = Lists.newArrayList();
        userIds.forEach( userId -> {
            roleIds.forEach( roleId -> {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setRoleId(roleId);
                sysRoleUser.setUserId(userId);
                sysRoleUser.setCreateTime(LocalDateTime.now());
                roleUserList.add(sysRoleUser);
            });
        });
        this.saveBatch(roleUserList);
    }

    public void deleteByUserIds(List<Long> userIds) {
        QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
        wrapper.in("user_id",userIds);
        this.remove(wrapper);
    }
}
